const { defineConfig } = require('@vue/cli-service');
const path = require('path');
const chalk = require('chalk');
const apiConfig = require('./src/lib/js/api.config');
const ip = require('./src/lib/js/getLocalIP');

const resolve = (dir) => {
  return path.join(__dirname, dir);
};

let MY_ENV = process.env.MY_ENV;
console.log(chalk.yellow(`  当前环境：${MY_ENV}\n`));
console.log(
  chalk.yellow(`  当前域名：${require('./src/lib/js/api.config')(MY_ENV)}\n`)
);
const IS_PROD = process.env.NODE_ENV === 'production';
const proxy = IS_PROD
  ? null
  : {
      '/apiProxy': {
        target: apiConfig(MY_ENV),
        secure: true,
        changeOrigin: true,
        // 如果本身的接口地址就有 '/api' 这种通用前缀，也就是说https://www.exaple.com/api，就可以把 pathRewrite 删掉
        pathRewrite: {
          '^/apiProxy': ''
        }
      }
    };
const devServer = {
  proxy,
  open: true,
  host: ip
};
function addStyleResource(rule) {
  rule
    .use('style-resource')
    .loader('style-resources-loader')
    .options({
      patterns: [path.resolve(__dirname, './src/lib/styles/var.less')]
    });
}
module.exports = defineConfig({
  transpileDependencies: true,
  chainWebpack: (config) => {
    // 移除 prefetch 插件
    config.plugins.delete('prefetch');
    // 设置别名引入
    config.resolve.alias
      .set('@', resolve('src'))
      .set('lib', resolve('src/lib'))
      .set('utils', resolve('src/utils'))
      .set('api', resolve('src/api'))
      .set('mixins', resolve('src/mixins'))
      // <img src="" /> / css的background调用方式 ～assets/xxx/xxx.jpg，js直接assets/xxx/xxx.jpg
      .set('assets', resolve('src/assets'))
      .set('components', resolve('src/components'))
      .end();

    // 设置全局变量 MY_ENV
    config
      .plugin('define')
      .tap((args) => {
        args[0]['process.env.MY_ENV'] = JSON.stringify(MY_ENV);
        console.log('args :', args);
        return args;
      })
      .end();
    // 导入全局的less变量
    const types = ['vue-modules', 'vue', 'normal-modules', 'normal'];
    types.forEach((type) =>
      addStyleResource(config.module.rule('less').oneOf(type))
    );
    if (process.env.NODE_ENV === 'production') {
      if (process.env.npm_config_report) {
        config
          .plugin('webpack-bundle-analyzer')
          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
          .end();
      }
    }
  },
  devServer
});
